package com.example.testapplication;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class NetworkActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView mTextView;
    private Button mButton;
    private static final String TAG = "NetworkActivity";
    private String mResult;
    private Button mParseDataButton;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network);
        
        findViews();  // 获取view
        setListeners(); // 设置点击事件
    }



    private void findViews() {
        mTextView = findViewById(R.id.textView);
        mButton = findViewById(R.id.getButton);
        mParseDataButton = findViewById(R.id.parseDataButton);
    }
    private void setListeners() {
        mButton.setOnClickListener(this);
        mParseDataButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.getButton:  // 请求数据
                //  <uses-permission android:name="android.permission.INTERNET"/>
                new Thread(new Runnable() {  // 注意 1.不能在主线程去操作 2.安全权限
                    @Override
                    public void run() {
                        String urlString = "http://www.imooc.com/api/teacher?type=2&page=1";
                        mResult = requestDataByGet(urlString);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mResult = decode(mResult);
                                mTextView.setText(mResult);
                            }
                        });
                    }
                }).start();
                break;
            case R.id.parseDataButton:
                if(!TextUtils.isEmpty(mResult)){
                    handleJSONData(mResult);
                }
                break;
        }
        
    }
    // get 请求
    private String requestDataByGet(String urlString){
        String result = null;
        try{
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);  // 设置超时时间
            connection.setRequestMethod("GET");  // 请求方式
            connection.setRequestProperty("Content-Type","application/json"); // 设置请求类型
            connection.setRequestProperty("Charset","UTF-8"); // 这种返回类型
            connection.setRequestProperty("Accept-Charset","UTF-8"); // 这种返回类型
            connection.connect(); // 发起连接
            int responseCode = connection.getResponseCode();  // 获取请求码
            if(responseCode == HttpURLConnection.HTTP_OK){
                InputStream inputStream = connection.getInputStream();
                result = streamToString(inputStream);
            }else{
                // ERROR fail
                String responseMessage = connection.getResponseMessage();  // 获取请求msg
                Log.e(TAG,"requestDataByPost:" + responseMessage);
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return result;
    }

    // post请求
    private String requestDataByPost(String urlString){
        String result = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(30000);
            connection.setRequestMethod("POST");
            // 设置运行输入，输出
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // post方式不能缓存，需手动设置为false
            connection.setUseCaches(false);
            connection.connect();
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  将输入流转换成字符串
     *   @param is 从网络获取的输入流
     *   @return 字符串
     * */

    public String streamToString(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) !=-1){
                baos.write(buffer,0,len);
            }
            baos.close();
            is.close();
            byte[] byteArray = baos.toByteArray();
            return new String(byteArray);

        }catch (Exception e){
            Log.e(TAG,e.toString());
            return null;

        }
    }
    /**
     * 工具类
     * 将Unicode字符转换为UTF-8类型字符串
     */
    public static String decode(String unicodeStr) {
        if (unicodeStr == null) {
            return null;
        }
        StringBuilder retBuf = new StringBuilder();
        int maxLoop = unicodeStr.length();
        for (int i = 0; i < maxLoop; i++) {
            if (unicodeStr.charAt(i) == '\\') {
                if ((i < maxLoop - 5)
                        && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr
                        .charAt(i + 1) == 'U')))
                    try {
                        retBuf.append((char) Integer.parseInt(unicodeStr.substring(i + 2, i + 6), 16));
                        i += 5;
                    } catch (NumberFormatException localNumberFormatException) {
                        retBuf.append(unicodeStr.charAt(i));
                    }
                else {
                    retBuf.append(unicodeStr.charAt(i));
                }
            } else {
                retBuf.append(unicodeStr.charAt(i));
            }
        }
        return retBuf.toString();
    }
    // 解析数据
    private void handleJSONData(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);

            LessonResult lessonResult = new LessonResult();
            List<LessonResult.Lesson> lessonList = new ArrayList<>();
            int status = jsonObject.getInt("status");
            JSONArray lessons = jsonObject.getJSONArray("data");
            if (lessons != null && lessons.length() > 0) {
                for (int index = 0; index < lessons.length(); index++) {
                    JSONObject item = (JSONObject) lessons.get(0);
                    int id = item.getInt("id");
                    String name = item.getString("name");
                    String smallPic = item.getString("picSmall");
                    String bigPic = item.getString("picBig");
                    String description = item.getString("description");
                    int learner = item.getInt("learner");

                    LessonResult.Lesson lesson = new LessonResult.Lesson();
                    lesson.setID(id);
                    lesson.setName(name);
                    lesson.setSmallPictureUrl(smallPic);
                    lesson.setBigPictureUrl(bigPic);
                    lesson.setDescription(description);
                    lesson.setLearnerNumber(learner);
                    lessonList.add(lesson);
                }
                lessonResult.setStatus(status);
                lessonResult.setLessons(lessonList);
                mTextView.setText("data is : " + lessonResult.toString());
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
